<script setup lang="ts">
import { ref } from "vue";
import { formRules } from "../utils/rule";
import { FormProps } from "../utils/types";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { useDictionar } from "../utils/hook";
import AddFill from "@iconify-icons/ri/add-circle-line";
import Delete from "@iconify-icons/ep/delete";

const { itemColumns } = useDictionar();

const props = withDefaults(defineProps<FormProps>(), {
  formInline: () => ({
    id: "",
    dictionaryName: "",
    dictionaryCode: "",
    itemList: []
  })
});

const ruleFormRef = ref();
const newFormInline = ref(props.formInline);

function onAdd() {
  newFormInline.value.itemList.push({
    itemName: "",
    itemValue: ""
  });
}

function onDel(row) {
  const index = newFormInline.value.itemList.indexOf(row);
  if (index !== -1) newFormInline.value.itemList.splice(index, 1);
}

function getRef() {
  return ruleFormRef.value;
}

defineExpose({ getRef });
</script>

<template>
  <el-form
    ref="ruleFormRef"
    :model="newFormInline"
    :rules="formRules"
    label-width="90px"
  >
    <el-row>
      <el-col :span="16" class="m-auto">
        <el-form-item label="字典名称" prop="dictionaryName">
          <el-input
            v-model="newFormInline.dictionaryName"
            clearable
            placeholder="请输入字典名称"
          />
        </el-form-item>
      </el-col>

      <el-col :span="16" class="m-auto">
        <el-form-item label="字典编码" prop="dictionaryCode">
          <el-input
            v-model="newFormInline.dictionaryCode"
            clearable
            placeholder="请输入字典名称"
          />
        </el-form-item>
      </el-col>
      <el-col :span="16" class="m-auto mb-6">
        <el-form-item label="字典键值对" prop="itemList">
          <pure-table
            row-key="id"
            align-whole="center"
            :header-cell-style="{
              background: 'var(--el-fill-color-light)',
              color: 'var(--el-text-color-primary)'
            }"
            :data="formInline.itemList"
            :columns="itemColumns"
            height="270"
            border
          >
            <template #append>
              <el-button
                plain
                class="!block !m-auto !my-4"
                :icon="useRenderIcon(AddFill)"
                @click="onAdd"
              >
                添加一行数据
              </el-button>
            </template>
            <template #operation="{ row }">
              <el-button
                class="reset-margin"
                link
                type="primary"
                :icon="useRenderIcon(Delete)"
                @click="onDel(row)"
              />
            </template>
          </pure-table>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>
